﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace Elentok.Common.Wpf.ValueConverters
{
  /// <summary>
  /// Converts numeric values to "#,#00 KB" display
  /// </summary>
  public sealed class SizeToKbConverter : IValueConverter
  {
    /// <summary>
    /// Converts numeric values to "#,#00 KB" display
    /// </summary>
    /// <param name="value"></param>
    /// <param name="targetType"></param>
    /// <param name="parameter"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      double number = 0;

      #region Get Bytes
      if (value is int)
        number = (double)(int)value;
      else if (value is decimal)
        number = (double)(decimal)value;
      else if (value is float)
        number = (double)(float)value;
      else if (value is double)
        number = (double)value;
      else
        throw new ArgumentException("Can't convert value of type " + value.GetType().Name, "value");
      #endregion

      number /= 1024;

      return string.Format("{0:#,###,##0} KB", number);
    }

    /// <summary>
    /// Converts from "#,#00 KB" display to integer
    /// </summary>
    /// <param name="value"></param>
    /// <param name="targetType"></param>
    /// <param name="parameter"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      string str = (string)value;
      str = str.Replace(",", "");
      str.Substring(0, str.Length - 3); // 3 = " KB"
      return int.Parse(str) * 1024;
    }
  }
}
